title | description | canonical | status | lastmod |
---|---|---|---|---|
The Fluent API HasMany Method |
Usage of the Fluent API HasMany Method in Entity Framework Core |
/configuration/fluent-api/hasmany-method |
Published |
2023-02-27 |
The Entity Framework Core Fluent API HasMany
method is used to configure the many side of a one-to-many relationship. The HasMany
method must be used in conjunction with the HasOne
method to fully configure a valid relationship, adhering to the Has/With pattern for relationship configuration.
The following model represents companies and employees with an inverse navigation property defined in the dependent entity (Employee
):
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Company Company { get; set; }
}
A company has many employees, each with one company. That relationship is represented as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>()
.HasMany(c => c.Employees)
.WithOne(e => e.Company);
}
Relationships can be defined with the ForeignKey and InverseProperty attributes.